# coding=utf-8
"""
    @Author：SimpleTree
    @date：2025/4/19 23:17
    @desc: 
"""
import hashlib

from django.db.models import QuerySet

from common.exception.app_exception import AppApiException
from common.models.db_model_manage import DBModelManage


def password_encrypt(raw_password):
    """
        密码 md5加密
        :param raw_password: 密码
        :return:  加密后密码
    """
    md5 = hashlib.md5()  # 2.实例化md5() 方法
    md5.update(raw_password.encode())  # 3，对字符串的字节类型加密
    result = md5.hexdigest()  # 4.加密
    return result


def encryption(message: str):
    """
        加密敏感字段数据  加密方式是 如果密码是 1234567890  那么给前端则是 123******890
    :param message:
    :return:
    """
    max_pre_len = 8
    max_post_len = 4
    message_len = len(message)
    pre_len = int(message_len / 5 * 2)
    post_len = int(message_len / 5 * 1)
    pre_str = "".join([message[index] for index in
                       range(0, max_pre_len if pre_len > max_pre_len else 1 if pre_len <= 0 else int(pre_len))])
    end_str = "".join(
        [message[index] for index in
         range(message_len - (int(post_len) if pre_len < max_post_len else max_post_len), message_len)])
    content = "***************"
    return pre_str + content + end_str

def post(post_function):
    def inner(func):
        def run(*args, **kwargs):
            result = func(*args, **kwargs)
            return post_function(*result)
        return run
    return inner

# 用于验证许可证（license）的有效性和数据记录数量是否超出限制
def valid_license(model=None, count=None, message=None):
    def inner(func):
        def run(*args, **kwargs):
            xpack_cache = DBModelManage.get_model('xpack_cache')
            is_license_valid = xpack_cache.get('XPACK_LICENSE_IS_VALID', False) if xpack_cache is not None else False
            record_count = QuerySet(model).count()
            if not is_license_valid and record_count >= count:
                error_message = message or f'超出限制{count}'
                raise AppApiException(400, error_message)
            return func(*args, **kwargs)
        return run
    return inner
